<?php

namespace Icsoc\DataBundle\Helper;

use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Validator\Constraints\Regex;
use Symfony\Component\Validator\Constraints\Type;

/**
 * 验证帮助类
 * Class ValidatorHelper
 * @package Icsoc\DataBundle\Helper
 */
class ValidatorHelper
{
    /**
     * @var \Symfony\Component\DependencyInjection\ContainerInterface
     */
    private $container;

    /**
     * @param $container
     */
    public function __construct($container)
    {
        $this->container = $container;
    }

    /**
     * 验证是否为数字
     *
     * @param string $field
     * @param string $value
     * @param string $code
     *
     * @return array|string
     */
    public function isNumeric($field, $value, $code)
    {
        $type = new Type(array('type'));
        $type->type = 'numeric';
        $type->message = $field." 不是数字";
        $error_list = $this->container->get('validator')->validateValue($value, $type);
        if (count($error_list) > 0) {
            $ret = array('code'=>$code, 'message'=>$error_list[0]->getMessage());
            return $ret;
        }
        return '';
    }

    /**
     * @param $message
     * @param $value
     * @param $code
     * @return array|string
     * 验证是否为日期格式；（eg:2012-05-29）
     */
    public function isDate($message, $value, $code)
    {
        $date = new Date();
        $date->message = $message;
        $error_list = $this->container->get('validator')->validateValue($value, $date);
        if (count($error_list) > 0) {
            $ret = array('code'=>$code, 'message'=>$error_list[0]->getMessage());
            return $ret;
        }
        return '';
    }

    /**
     * 验证时间格式00:00:00
     * @param $message
     * @param $date
     * @param $code
     * @return array|string
     */
    function isDateHour($message, $date, $code)
    {
        //匹配日期格式
        $ret = array('code'=>$code, 'message'=>$message);
        if (preg_match("/^([0-1][0-9]|2[0-3])\:([0-5][0-9])\:([0-5][0-9])$/", $date, $parts)) {
            //检测是否为日期
            return '';
        } else {
            return $ret;
        }
    }

    /**
     * @param $message
     * @param $value
     * @param $code
     * @return array|string
     * 验证是否为日期格式；（eg:2012-05-29 05:50:23)
     */
    public function isDateTime($message, $value, $code)
    {
        $date = new DateTime();
        $date->message = $message;
        $error_list = $this->container->get('validator')->validateValue($value, $date);
        if (count($error_list) > 0) {
            $ret = array('code'=>$code, 'message'=>$error_list[0]->getMessage());
            return $ret;
        }
        return '';
    }

    /**
     * @param $reg （正则）
     * @param $value （值）
     * @param $message （错误信息）
     * @param $code （错误代码）
     * @return array|string
     * 正则验证格式的正确性；
     */
    public function regexRormat($reg, $value, $message, $code)
    {
        $regex = new Regex(array('pattern'));
        $regex->pattern = $reg;
        $regex->message = $message;
        $error_list = $this->container->get('validator')->validateValue($value, $regex);
        if (count($error_list) > 0) {
            $ret = array('code'=>$code, 'message'=>$error_list[0]->getMessage());
            return $ret;
        }
        return '';
    }

    /**
     * 验证某一个字段是否属于某张表；
     *
     * @param string $field
     * @param string $table
     *
     * @return bool
     */
    public function fieldExistTable($field, $table)
    {
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $list = $conn->fetchAll('DESC '.$table);
        if (empty($list)) {
            return false ;
        }
        $fields = array();
        foreach ($list as $v) {
            $fields[] = $v['Field'];
        }
        if (in_array($field, $fields)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $count
     * @param $table
     * @param $addInfo
     * @return array
     * 获取分页信息
     */
    public function getPageInfo($count, $table, $addInfo)
    {
        $limit = isset($addInfo['pagination']['rows']) ?  $addInfo['pagination']['rows'] : 100000;
        $total_pages = ceil($count/$limit);
        $page = isset($addInfo['pagination']['page']) ? $addInfo['pagination']['page'] : 1;
        $page = $page > $total_pages ? $total_pages : $page;
        $start = $limit*$page - $limit;
        $start = $start > 0 ? $start : 0;
        $flag = false;
        if (isset($addInfo['sort']['field'])) {
            //就需要验证传入字段是否属于坐席表
            $flag = $this->fieldExistTable($addInfo['sort']['field'], $table);
        }
        $sort = $flag ? $addInfo['sort']['field'] : 1;
        $order = isset($addInfo['sort']['order']) &&
            in_array(strtolower($addInfo['sort']['order']), array('desc','asc'))
            ? $addInfo['sort']['order'] : 'desc';
        return array('start'=>$start, 'sort'=>$sort, 'order'=>$order,'limit'=>$limit,
            'totalPage'=>(int) $total_pages, 'page'=> (int) $page);
    }

    /**
     * 新的分页函数
     * @param $count
     * @param $table
     * @param $addInfo
     * @return array
     */
    public function getPageInfoExt($count, $table, $addInfo)
    {
        $limit = isset($addInfo['pagination']['rows']) ?  $addInfo['pagination']['rows'] : 100000;
        $total_pages = ceil($count/$limit);
        $page = isset($addInfo['pagination']['page']) ? $addInfo['pagination']['page'] : 1;
        $page = $page > $total_pages ? $total_pages : $page;
        $start = $limit*$page - $limit;
        $start = $start > 0 ? $start : 0;
        $order = isset($addInfo['sort']['order']) &&
        in_array(strtolower($addInfo['sort']['order']), array('desc','asc'))
            ? $addInfo['sort']['order'] : 'desc';
        $sort = "1 $order";
        if (isset($addInfo['sort']['field']) && is_array($addInfo['sort']['field'])) {
            //就需要验证传入字段是否属于坐席表
            foreach ($addInfo['sort']['field'] as $val) {
                $flag = $this->fieldExistTable($val, $table);
                $sort.= ($flag ? (','.$val.' '.$order) : '');
            }
        } elseif (isset($addInfo['sort']['field'])) {
            $flag = $this->fieldExistTable($addInfo['sort']['field'], $table);
            $sort = $flag ? $addInfo['sort']['field'] : 1;
            $order = isset($addInfo['sort']['order']) &&
            in_array(strtolower($addInfo['sort']['order']), array('desc','asc'))
                ? $addInfo['sort']['order'] : 'desc';
            $sort = $sort.',id '.$order;
        }
        return array('start'=>$start, 'sort'=>$sort,'limit'=>$limit,
            'totalPage'=>(int) $total_pages, 'page'=> (int) $page);
    }

    /**
     * @param $filter
     * @param $info
     * @return String
     * 拼凑 like 语句
     */
    public function likeWhere($filter, $info)
    {
        $where = '';
        foreach ($filter as $v) {
            if (isset($info[$v]) && !empty($info[$v])) {
                $where.=" AND $v like '%".$info[$v]."%' ";
            }
        }
        return $where;
    }

    /**
     * @param $filter
     * @param $info
     * @return array
     * 拼凑 >=  <=
     */
    public function ltRtWhere($filter, $info)
    {
        $where = '';
        $params = array();
        foreach ($filter as $v) {
            $min = 'min_'.$v;
            $max = 'max_'.$v;
            if (isset($info[$min]) && !empty($info[$min])) {
                $where.=" AND $v >= :$min ";
                $params[$min] = $info[$min];
            }
            if (isset($info[$max]) && !empty($info[$max])) {
                $where.=" AND $v <= :$max ";
                $params[$max] = $info[$max];
            }
        }
        return array('where'=>$where,'params'=>$params);
    }

    /**
     * @param $filter
     * @param $info
     * @return array
     * 拼凑 =
     */
    public function equalWhere($filter, $info)
    {
        $where = '';
        $params = array();
        foreach ($filter as $v) {
            if (isset($info[$v]) && $info[$v] !== '') {
                $where.=" AND $v = :$v ";
                $params[$v] = $info[$v];
            }
        }
        return array('where'=>$where,'params'=>$params);
    }

    /**
     * @param $addInfo
     * @param $timeField
     * @return string
     * 拼接时间
     */
    public function dateTimeWhere($addInfo, $timeField = 'start_time')
    {
        $where = '';
        if (isset($addInfo['start_time']) && !empty($addInfo['start_time'])) {
            $start_time = $addInfo['start_time'];
            $msg = $this->container->get('icsoc_data.helper')->isDateTime('开始时间格式不正确', $start_time, 404);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
            $where.="AND $timeField >= UNIX_TIMESTAMP('$start_time') ";
        }

        //结束时间
        if (isset($addInfo['end_time']) && !empty($addInfo['end_time'])) {
            $end_time = $addInfo['end_time'];
            $msg = $this->container->get('icsoc_data.helper')->isDateTime('结束时间格式不正确', $end_time, 405);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
            $where.="AND $timeField <= UNIX_TIMESTAMP('$end_time') ";
        }
        return $where;
    }

    /**
     * @param int $len
     * @return string
     * 随机字符串
     */
    public function randString($len = 8)
    {
        $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $str = '';
        for ($i=0; $i < $len; $i++) {
            $str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
        }
        return $str;
    }
}
